在C++中,通信是一种 流动,而非静态的存储事件。 iostream 库采用了一种 多态层次结构 其中专门类如 ifstream (文件)和 istringstream (内存)从 istream继承而来。这实现了 流继承:为基类流设计的函数可以透明地处理来自任何源的数据。
不可复制的约束
流代表与硬件的唯一、有状态的连接。为防止多个对象争夺同一个文件指针或控制台缓冲区,输入输出对象 不能被复制或赋值。尝试编写如下代码 ofstream out1, out2; out1 = out2; 将导致编译器错误。因此,输入输出对象必须通过 非常量引用传递。
顺序桥梁
虽然流提供了接口, 顺序容器 (vector, list)提供内存。流进来的数据通常被组织成这些容器,根据速度选择 vector 以获得速度,或选择 list 以实现灵活插入。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What causes the termination of
while (cin >> i)?The stream reaching a value of 0.
Encountering end-of-file (EOF) or an invalid input type.
The buffer becoming full.
A semicolon in the input stream.
✅ Correct!
Correct. The expression evaluates to the stream itself, which in a boolean context returns false if the stream's failbit or eofbit is set.❌ Incorrect
The while loop terminates when the stream state becomes invalid, such as entering a character when an integer was expected.QUESTION 2
Identify the error:
ofstream out1, out2; out1 = out2;Logic error: Files cannot have the same name.
Syntax error: Stream assignment is prohibited.
Runtime error: Buffer overflow.
No error; this is standard C++ usage.
✅ Correct!
Stream objects are non-copyable and non-assignable to prevent ambiguous hardware management.❌ Incorrect
C++ deletes the copy constructor and assignment operator for IO classes.QUESTION 3
How should an
istream be passed to a function that reads from it?By value (e.g., void func(istream is))
By const reference (e.g., void func(const istream &is))
By non-const reference (e.g., void func(istream &is))
As a pointer to a const object.
✅ Correct!
Reading from a stream changes its internal state (e.g., position pointers), so it must be a non-const reference.❌ Incorrect
Since streams are non-copyable, 'by value' is impossible. Since reading modifies the stream, 'const reference' is invalid.QUESTION 4
What is the primary flaw in this loop?
while (iter1 < iter2) where iter is a list<int>::iterator?Lists only support
!= comparison for iterators.The loop will result in an infinite recursion.
List iterators must be decremented.
You cannot compare iterators of the same container.
✅ Correct!
Correct! Because lists are not stored contiguously, the < operator is not defined; use != instead.❌ Incorrect
The < operator is only defined for random-access iterators (like vector or deque).QUESTION 5
Why would you call
is.clear() before returning an istream& from a function?To delete all data within the stream.
To reset the error state (like EOF) so the caller can continue using it.
To flush the output buffer.
To close the associated file handle.
✅ Correct!
Once a stream hits EOF, it remains in an error state. clear() resets the state bits.❌ Incorrect
clear() affects the state flags, not the data contents or file connection.Case Study: The polymorphic Logging & Storage System
Managing Stream IO and Sequential Containers
You are designing a system that reads user input and stores it. You need a function that can read from either the standard console (cin) or a file, stores every word individually, and returns the stream to a healthy state for the next component.
Q
1. Implement Exercise 8.1: Write the C++ function that reads an istream until EOF, prints the content, and resets the stream.
Solution:
The function would look like this:
The function would look like this:
istream& readAndReset(istream &is) {
string val;
while (is >> val) {
cout << val << endl;
}
is.clear(); // Essential to reset EOF state
return is;
}Q
2. Provide a usage guide for when to select: vector, list, deque, map, and set.
Solution:
vector: Best for fast random access and adding elements at the end. list: Best for frequent insertions/deletions anywhere in the container. deque: Best for insertions/deletions at both ends (queues). map: Best for key-value pairs where fast lookups by key are needed. set: Best for maintaining a sorted collection of unique elements.
vector: Best for fast random access and adding elements at the end. list: Best for frequent insertions/deletions anywhere in the container. deque: Best for insertions/deletions at both ends (queues). map: Best for key-value pairs where fast lookups by key are needed. set: Best for maintaining a sorted collection of unique elements.
Q
3. Exercise 8.5: How would you modify a program to store each word of a file into a vector of strings?
Solution:
By using the extraction operator
By using the extraction operator
>>, which naturally stops at whitespace: string word;
while (inputFile >> word) {
vec.push_back(word);
} This differs from getline(), which reads whole lines including spaces.